package org.xxpay.pay.channel.ywxpay;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.entity.PayPassageAccount;
import org.xxpay.core.entity.WxUser;
import org.xxpay.pay.service.CommonService;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: dingzhiwei
 * @date: 19/1/22
 * @description: 用户状态同步任务
 */
@Component
public class YwxpayScheduled {

    @Autowired
    private CommonService commonService;

    @Autowired
    private YwxpayService ywxpayService;

    private static final MyLog _log = MyLog.getLog(YwxpayScheduled.class);

    /**
     * 同步微信用户状态任务
     */
    //@Scheduled(cron="0 0/1 * * * ?") //每分钟执行一次
    public void payReissueTask() {
        String logPrefix = "【WX状态同步】";
        int pageIndex = 1;
        int limit = 100;
        boolean flag = false;
        _log.info("{}开始查询所有微信用户", logPrefix);
        Map<String, YwxpayConfig> configMap = getServerMap();
        // 循环查询所有
        while (flag) {
            WxUser queryWxUser = new WxUser();
            List<WxUser> wxUserList = commonService.wxUserService.select4sync((pageIndex - 1) * limit, limit);
            _log.info("{}查询需要处理的微信用户,共:{}条", logPrefix, wxUserList == null ? 0 : wxUserList.size());
            for(WxUser wxUser : wxUserList) {
                Long startTime = System.currentTimeMillis();
                String serverId = wxUser.getServerId();
                YwxpayConfig ywxpayConfig = configMap.get(serverId);
                if(ywxpayConfig == null) {
                    _log.info("{}没有配置子账账号,serverId={}", logPrefix, serverId);
                }
                JSONObject resObj = ywxpayService.getLoginStatus(ywxpayConfig.getReqUrl(), wxUser);
                if(resObj == null) {
                    continue;
                }
                String code = resObj.getString("code");
                if("0".equals(code)) {
                    JSONObject dataObj = resObj.getJSONObject("data");
                    Integer dataCode = dataObj.getInteger("code");
                    String dataMsg = dataObj.getString("msg");
                    WxUser updateWxUser = new WxUser();
                    updateWxUser.setLoginStatus(dataCode);
                    updateWxUser.setLoginResult(dataMsg);
                    updateWxUser.setLoginSyncTime(new Date());
                    int updateCount = commonService.wxUserService.updateByRandomId(updateWxUser, wxUser.getRandomId());
                    _log.info("{}userId={},randomId={},loginStatus={},loginResult={},updateCount={}", logPrefix, wxUser.getUserId(), wxUser.getRandomId(), dataCode, dataMsg, updateCount);
                }else if("1002".equals(code)) {
                    // 用户线程不存在，表示用户已离线
                    WxUser updateWxUser = new WxUser();
                    Integer dataCode = -1;
                    String dataMsg = "未登录";
                    updateWxUser.setLoginStatus(dataCode);
                    updateWxUser.setLoginResult(dataMsg);
                    updateWxUser.setLoginSyncTime(new Date());
                    int updateCount = commonService.wxUserService.updateByRandomId(updateWxUser, wxUser.getRandomId());
                    _log.info("{}userId={},randomId={},loginStatus={},loginResult={},updateCount={}", logPrefix, wxUser.getUserId(), wxUser.getRandomId(), dataCode, dataMsg, updateCount);
                }else {
                    _log.info("{}userId={},randomId={},code={},未处理", logPrefix, wxUser.getUserId(), wxUser.getRandomId(), code);
                }
                _log.info("{}同步完毕userId={},randomId={}.耗时:{} ms", logPrefix, wxUser.getUserId(), wxUser.getRandomId(), System.currentTimeMillis() - startTime);
            }
            pageIndex++;
            if(CollectionUtils.isEmpty(wxUserList) || wxUserList.size() < limit) {
                flag = false;
            }
        }
        _log.info("{}本次同步用户状态完毕,", logPrefix);
    }

    /**
     * 得到云微信支付下配置子账户Map
     * @return
     */
    public Map getServerMap() {
        PayPassageAccount payPassageAccount = new PayPassageAccount();
        payPassageAccount.setIfTypeCode(YwxpayConfig.CHANNEL_NAME);
        List<PayPassageAccount> payPassageAccountList = commonService.payPassageAccountService.selectAll(payPassageAccount);
        Map<String, YwxpayConfig> configMap = new HashMap<>();
        if(CollectionUtils.isEmpty(payPassageAccountList)) return configMap;
        for(PayPassageAccount ppa : payPassageAccountList) {
            configMap.put(ppa.getPassageMchId(), new YwxpayConfig(ppa.getParam()));
        }
        return configMap;
    }

    /**
     * 初始化今日数据
     */
    @Scheduled(cron="0 0/1 * * * ?")
    public void initDay() {
        commonService.wxUserService.updateDayByInit();
    }

}
